<?php

use Illuminate\Database\Capsule\Manager as DB;

/**
 * @name 公司管理
 */
class CompanyController extends ACommonController
{
    protected $table = 'company';
    protected $model = 'companyModel';
    protected $primaryKey = 'id';
    protected $condition = [];

    public function getAction($returnData=false)
    {
        $keywords = $this->get('keywords');
        if (!empty($keywords)) {
            array_push($this->search, ['name', 'like', "%{$keywords}%", "or"]);
            array_push($this->search, ['code', 'like', "%{$keywords}%", "or"]);
        }
        $status = $this->get('status', 0);
        if ($status >= 0) {
            array_push($this->condition, ['status', '=', $status]);
        }
        $start_on = $this->get('start_on');
        if (!empty($start_on)) {
            array_push($this->condition, ['created_at', '>=', $start_on.' 00:00:00']);
        }
        $end_on = $this->get('end_on');
        if (!empty($end_on)) {
            array_push($this->condition, ['created_at', '<=', $end_on.' 23:59:59']);
        }
        parent::getAction();
    }

    /**
     * @name 添加公司处理
     */
    public function addAction()
    {
        if(!$this->isPost()){
            parent::addAction();
        }else {
            do {
                $companyRows = [
                    'name'        => $this->get('name'),
                    'contact'     => $this->get('contact'),
                    'tel'         => $this->get('tel'),
                    'licence'     => $this->get('licence'),
                    'licence_img' => $this->get('licence_img'),
                    'expired'     => $this->get('expired', 0),
                    'status'      => $this->get('status', 1),
                    'sortorder'   => $this->get('sortorder', 500),
                    'created_at'  => date('Y-m-d H:i:s')
                ];
                $roles       = [
                    'name'    => ['role' => "required|unique:company.name", 'msg' => '公司名称'],
                    'contact' => ['role' => "required", 'msg' => '联系人'],
                ];
                Validate::check($companyRows, $roles);
                $memberRows = [
                    'phone'      => $this->get('phone'),
                    'password'   => $this->get('password'),
                    'realname'   => $this->get('contact'),
                    'roles_id'   => 0,
                    'is_root'    => 1,
                    'status'     => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                $roles      = [
                    'phone'    => ['role' => "required|unique:members.phone", 'func' => 'isMobile', 'msg' => '主账号'],
                    'password' => ['role' => "required", 'msg' => '登陆密码'],
                ];
                Validate::check($memberRows, $roles);
                try {
                    DB::beginTransaction();
                    $company_id               = DB::table('company')->insertGetId($companyRows);
                    $rolesRow                 = [
                        'company_id' => $company_id,
                        'name'       => '企业管理员组',
                        'menu_ids'   => DB::table('members_menus')->pluck('id')->implode(','),
                        'created_at' => date('Y-m-d H:i:s')
                    ];
                    $roles_id                 = DB::table('members_roles')->insertGetId($rolesRow);
                    $memberRows['password']   = md5($memberRows['password']);
                    $memberRows['company_id'] = $company_id;
                    $memberRows['roles_id']   = $roles_id;
                    DB::table('members')->insert($memberRows);
                    DB::commit();
                    $result = [
                        'ret' => 0,
                        'msg' => '操作成功',
                    ];
                } catch (\Exception $e) {
                    DB::rollBack();
                    $result = [
                        'ret' => 3,
                        'msg' => '数据插入失败',
                        'data'=> $e->getMessage(),
                    ];
                }
            } while (FALSE);
            json($result);
        }
    }

    /**
     * @name 编辑会员处理
     */
    public function editAction()
    {
        if($this->isPost()){
            $rows  = $this->postData;
            $roles = [
                'id'   => ['role' => "required|exists:company.id", 'msg' => '公司ID'],
                'name' => ['role' => "required", 'msg' => '公司名称'],
            ];
            Validate::check($rows, $roles);

            $infoRows = $rows['info'];
            $this->cleanTableColumn('company_info', $infoRows);
            DB::table('company_info')->where('company_id', $infoRows['company_id'])->update($infoRows);

            $membersRows = $rows['members'];
            $roles = [
                'id' => ['role' => "required|exists:members.id", 'func' => 'isInt', 'msg' => '会员ID'],
                'username' => ['role' => "required", 'msg' => '会员账号'],
            ];
            Validate::check($membersRows, $roles);
            $membersRows['updated_at'] = date('Y-m-d H:i:s');
            if($membersRows['newpassword']!==''){
                $membersRows['password'] = md5($membersRows['password']);
            }
            if($membersRows['expired_modify']!==''){
                $membersRows['expired'] = strtotime($membersRows['expired_modify']);
            }
            $membersRows['status'] = isset($membersRows['status']) && ($membersRows['status'] == 1 || $membersRows['status'] == 'true') ? 1 : 0;
            unset($membersRows['created_at'],$membersRows['lockuntil'],$membersRows['logined_at'],$membersRows['logined_ip'],$membersRows['score']);
            $this->cleanTableColumn('members', $membersRows);
            DB::table('members')->where('id', $membersRows['id'])->update($membersRows);

            $membersinfoRows = $rows['members_info'];
            $this->cleanTableColumn('members_info', $membersinfoRows);
            DB::table('members_info')->where('company_id', $membersinfoRows['company_id'])->update($membersinfoRows);
        }
        $this->_view->assign('industry', DB::table('industry')->get());
        $this->_view->assign('rank', DB::table('members_rank')->get());
        $this->_view->assign('city', (new cityModel)->getCityRows(2));
        parent::editAction();
    }

    /**
     * @name 企业状态
     */
    public function statusAction()
    {
        do {
            $id     = $this->get('id', 0);
            $status = $this->get('status', 0);
            if (DB::table('company')->where('id', $id)->update(['status' => $status]) !== FALSE) {
                $result = [
                    'ret' => 0,
                    'msg' => '操作成功',
                ];
            } else {
                $result = [
                    'ret' => 2,
                    'msg' => '数据更新失败',
                ];
            }
        } while (FALSE);

        json($result);
    }

    /**
     * @name 编辑会员
     */
    public function viewAction($flag = FALSE)
    {
        ret(0, '公司详情', (new companyModel())->find($this->get('id')));
    }

    /**
     * @name 获取公司权限
     */
    public function getRoleAction()
    {
        ret(0, '公司权限组', DB::table('members_roles')->where('company_id', $this->get('company_id'))
            ->where('group_id', $this->get('group_id'))
            ->get());
    }

    /**
     * @name 公司权限列表
     */
    public function menuendAction()
    {
        $controllerdir = Yaf_Registry::get('config')['application']['directory'] . '/controllers';
        $filenames     = scandir($controllerdir);
        $dataset       = [];
        foreach ($filenames as $v) {
            if (!is_dir($v)) {
                $v = substr($v, 0, -4);
                if (!in_array($v, ['BCommon', 'BCore', 'Common', 'Core', 'Error', 'Public'])) {
                    $dataset[$v] = $this->getact($v);
                }
            }
        }
        ret(0, '公司权限列表', $dataset);
    }

    private function getact(string $controller = '', array $actions = [])
    {
        do {
            $rows = [];
            if (empty($controller)) {
                break;
            }
            $controller_file = Yaf_Registry::get('config')['application']['directory'] . '/controllers/' . $controller . '.' . Yaf_Registry::get('config')['application']['ext'];
            require_once($controller_file);
            $reflector = new ReflectionClass($controller . 'Controller');
            foreach ($reflector->getMethods() as $k => $v) {
                if (strstr($v->name, 'Action')) {
                    $value = substr($v->name, 0, -6);
                    $notes = $reflector->getMethod($v->name)->getDocComment();
                    if (preg_match('#@name\s(.*?)\s#msix', $notes, $name) > 0) {
                        $name = $name[1];
                    } else {
                        $name = $value;
                    }
                    array_push($rows, [
                        'name'  => $name,
                        'value' => $value,
                        'flag'  => in_array($value, $actions),
                        'url'   => strtolower("/{$this->module}/{$controller}/{$value}")
                    ]);
                }
            }
        } while (FALSE);
        return $rows;
    }


}
